//
//  FindRecomViewController.m
//  SXH
//
//  Created by 房 国生 on 15/8/5.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "FindRecomViewController.h"
#import "FindRecomTableViewCell.h"
#import "MJRefresh.h"
#import "CommonService.h"
#import "UserRecomEntity.h"
#import "UIImageView+WebCache.h"
#import "UserEntity.h"
#import "FindEntity.h"
#import "LoginViewController.h"
#import "FindMeViewController.h"

@interface FindRecomViewController ()<FindRecomTableViewDelegate> {
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}

@property (nonatomic, strong) NSMutableArray *mutableArrayRecom;
@property (nonatomic, strong) IBOutlet UITableView *tableViewRecom;

@end

@implementation FindRecomViewController
@synthesize mutableArrayRecom, tableViewRecom;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    mutableArrayRecom = [[NSMutableArray alloc] init];
    
//    [self.tableViewRecom.layer setMasksToBounds:YES];
//    [self.tableViewRecom.layer setCornerRadius:2.0]; //设置矩形四个圆角半径
//    [self.tableViewRecom.layer setBorderWidth:1.0]; //边框宽度
//    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.77, 0.77, 0.77, 1 });
//    [self.tableViewRecom.layer setBorderColor:colorref];//边框颜色
//
    page = 1;
    [self addHeader];
    [self addFooter];
    tableViewRecom.showsVerticalScrollIndicator = NO;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayRecom count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"FindRecomTableViewCell";
    FindRecomTableViewCell *cell = (FindRecomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindRecomTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.delegate = self;
    }
    
    if ([mutableArrayRecom count] < indexPath.row) {
        return cell;
    }
    UserRecomEntity *entity = [mutableArrayRecom objectAtIndex:indexPath.row];
    
    cell.labelName.text = entity.userEntity.nickName;
    cell.labelDes.text = entity.userEntity.signature;
    cell.btnAdd.tag = indexPath.row;
    [cell.imageViewHeader sd_setImageWithURL:[NSURL URLWithString:entity.userEntity.userAlbum]];
    [cell.imageViewHeader.layer setMasksToBounds:YES];
    [cell.imageViewHeader.layer setCornerRadius:20.0]; //设置矩形四个圆角半径
    cell.img_height.constant = SCREEN_WIDTH / 4.0f;
    NSArray *array = [[NSArray alloc] initWithObjects:cell.imageViewLeft, cell.imageViewMiddle1, cell.imageViewMiddle2, cell.imageViewRight,nil];
    
    for (int i = 0; i < [array count] && i < [entity.mutableArrayTravel count]; i++) {
        UIImageView *imageView = [array objectAtIndex:i];
        FindEntity *findEntity = [entity.mutableArrayTravel objectAtIndex:i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:findEntity.album_thumb]];
    }
    
    if ([entity.userEntity.isVip isEqualToString:@"0"] == YES) {
        cell.imageViewVIP.hidden = YES;
    }
    
    if ([entity.userEntity.attention_flag intValue] == 1) {
        [cell.btnAdd setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 135 + SCREEN_WIDTH/4.0 - 80;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UserRecomEntity *entity = [mutableArrayRecom objectAtIndex:indexPath.row];
    
    FindMeViewController *vc = [[FindMeViewController alloc] init];
    vc.userId = entity.userEntity.userId;
    if (self.mainVC != nil) {
        [self.wrapperMainVC.navigationController pushViewController:vc animated:YES];
    } else {
        [self.wrapperMainVC.navigationController pushViewController:vc animated:YES];
    }
}

- (void)spotButtonAction:(NSInteger) tag {
    
}

- (void) getUserRecommData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           strPageNo, @"page",
                           @"20", @"limit",
                           userEntity.userId, @"userid",nil];
    
    [service getNetWorkData:param
                       Path:USER_QUERY_RECOMMEND
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      for (NSDictionary* attributes in array) {
                          UserRecomEntity *entity = [[UserRecomEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [mutableArrayRecom addObject:entity];
                      }
                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                  }];
}

- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewRecom;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getUserRecommData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewRecom;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [mutableArrayRecom removeAllObjects];
        [self getUserRecommData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewRecom reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

/* server will return the image width and hegiht, so this function will no use.
 
 -(void) lk_finishDownLoad:(UIImage*)image {
 DebugLog(@"imageView = %f, %f", image.size.width, image.size.height);
 }
 */

- (void)addWatchAction:(UIButton *) btn {
    UserRecomEntity *entity = [mutableArrayRecom objectAtIndex:btn.tag];
    if ([entity.userEntity.attention_flag intValue] == 1) {
        return;
    }
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.userId == nil) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        if (_mainVC != nil) {
            [_wrapperMainVC.navigationController pushViewController:vc animated:YES];
        } else {
            [_wrapperMainVC.navigationController pushViewController:vc animated:YES];
        }
    } else {
        CommonService *service = [[CommonService alloc] init];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               entity.userEntity.userId,@"attention_id",
                               userEntity.userId,@"userid",
                               nil];
        
        [service getNetWorkData:param
                           Path:USER_ATTENTION
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          NSNumber *code = [dic objectForKey:@"code"];
                          if ([code intValue] == 0) {
                              [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                              ALERT_ERR_MSG(@"关注成功");
                              [mutableArrayRecom removeObjectAtIndex:btn.tag];
                              [self.tableViewRecom reloadData];
                          } else {
                              ALERT_ERR_MSG(@"关注失败");
                          }
                      } Failed:^(NSInteger errorCode, NSString *message) {
                      }];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FindRecomViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FindRecomViewController"];
}
@end
